#ifndef TB_ARCHIVE_JSON_PARSER_HPP__
#define TB_ARCHIVE_JSON_PARSER_HPP__

#include <rapidjson/document.h>

#include "../base/memory_buffer.hpp"

#include "stream/json_input_stream.hpp"
#include "archive_export.hpp"

TB_NAMESPACE_BEGIN

template <typename BufferType = MemoryBuffer>
struct JsonParser {

  typedef JsonInputStream<BufferType, TCHAR> JsonInputStreamType;

  typedef RAPIDJSON_NAMESPACE::UTF8<TCHAR> JsonEncodeType;

  typedef RAPIDJSON_NAMESPACE::GenericValue<JsonEncodeType> JsonValueType;

  typedef RAPIDJSON_NAMESPACE::GenericDocument<JsonEncodeType> JsonDocumentType;

  static bool ParseString(const String &param, JsonDocumentType &doc) {
    BufferType buf(TB_ASCII_STRING(param));
    JsonInputStreamType stream(buf);
    doc.ParseStream<RAPIDJSON_NAMESPACE::kParseStopWhenDoneFlag>(stream);
    return !doc.HasParseError();
  }

  static bool ParseBuffer(BufferType &buf, JsonDocumentType &doc) {
    JsonInputStreamType stream(buf);
    doc.ParseStream<RAPIDJSON_NAMESPACE::kParseStopWhenDoneFlag>(stream);
    return !doc.HasParseError();
  }

  static bool ParseFile(const String &filePath, JsonDocumentType &doc) {
    BufferType buf;
    File::ReadBinary(filePath.c_str(), buf);
    JsonInputStreamType stream(buf);
    doc.ParseStream<RAPIDJSON_NAMESPACE::kParseStopWhenDoneFlag>(stream);
    return !doc.HasParseError();
  }
};

typedef JsonParser<> DefaultJsonParser;

TB_NAMESPACE_END

#endif // TB_ARCHIVE_JSON_PARSER_HPP__
